package com.fruit.service.user.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.mapper.user.SysRoleMapper;
import com.fruit.mapper.user.SysUserMapper;
import com.fruit.pojo.role.SysRole;
import com.fruit.pojo.user.SysUser;
import com.fruit.service.user.SysUserManager;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

@Service("sysUserService")
public class SysUserService implements SysUserManager{

	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Autowired
	private SysRoleMapper sysRoleMapper;
	
	@Override
	public SysUser getUserInfo(SysUser sysUser) {
		return sysUserMapper.getUserInfo(sysUser);
	}

	@Override
	public Map<String, Object> saveLogin(SysUser sysUser) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		
		SysUser sysUserInfo = sysUserMapper.getUserInfo(sysUser);
		if(sysUserInfo == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户名不存在!"));
			return resMap;
		}
		String pwHash = new SimpleHash("SHA-1", sysUser.getUserName(), sysUser.getPassword()).toString(); // 密码加密
		if(!StringUtils.equals(pwHash, sysUserInfo.getPassword())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "password_error", "登录密码错误!"));
			return resMap;
		}
		SysRole sr = sysRoleMapper.getRoleInfo(sysUserInfo.getRoleId());
		if(sr != null){
			sysUserInfo.setRoleName(sr.getRoleName());
		}
		sysUserInfo.setLastLogin(DateUtil.getTime());
		sysUserMapper.updateLastLogin(sysUserInfo);

		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "登录成功!"));
		resMap.put("sysUser", sysUserInfo);
		return resMap;
	}

	@Override
	public List<SysUser> getTransactionNum(SysUser sysUser) {
		return sysUserMapper.getTransactionNum(sysUser);
	}

	@Override
	public List<SysUser> getOrderNum(SysUser sysUser) {
		return sysUserMapper.getOrderNum(sysUser);
	}

	
	
}
